<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>角色管理</title>
    <script src="../js/axios-0.18.0.js"></script>
    <script src="../js/axios-interceptors.js"></script>
    <script src="../js/vue3.js"></script>
    <script src="../js/element-plus.js"></script>
    <script src="../js/icons-vue.js"></script>
    <script src="../js/zh-cn.js"></script>
    <link href="../css/index.css" rel="stylesheet"/>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: "Helvetica Neue", Arial, sans-serif;
            background: #f4f6f9;
            display: flex;
            justify-content: center; /* 页面整体水平居中 */
        }

        .main-container {
            width: 100%;
            max-width: 1200px; /* 限制页面最大宽度，避免过宽 */
        }

        .table-container {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }

        .pagination-container {
            margin-top: 15px;
            display: flex;
            justify-content: center; /* 分页组件水平居中 */
        }

        /* 按钮交互效果优化 */
        .el-button {
            transition: all 0.3s ease;
            border-radius: 4px;
        }
        .el-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        /* 表格视觉优化 */
        .el-table {
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            width: 100% !important; /* 确保表格占满容器宽度 */
        }
        /* 为多选框添加边框样式 */
        .el-table .el-table__cell .el-checkbox__inner {
            border: 2px solid #666; /* 深灰色边框 */
            width: 18px; /* 稍微增大复选框 */
            height: 18px;
        }

        /* 选中状态的样式增强 */
        .el-table .el-table__cell .el-checkbox__input.is-checked .el-checkbox__inner {
            background-color: #409eff; /* 保持Element默认的蓝色 */
            border-color: #409eff;
        }

        /* hover状态增强 */
        .el-table .el-table__cell .el-checkbox__inner:hover {
            border-color: #409eff;
        }
    </style>
</head>
<body>
<div id="app" class="main-container">
    <!-- 角色表格区域 -->
    <div class="table-container">
        <el-table :data="tableData" border stripe>
            <el-table-column type="selection" width="45"></el-table-column>
            <!-- 移除固定宽度，添加flex-grow使列平均分配空间 -->
            <el-table-column prop="id" label="编号" align="center" :flex="1"></el-table-column>
            <el-table-column prop="roleName" label="角色名称" align="center" :flex="1"></el-table-column>
            <el-table-column prop="roleCode" label="角色编码" align="center" :flex="1"></el-table-column>
            <el-table-column label="操作" align="center" min-width="220">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    <el-button size="small" type="success" @click="getPermissionData(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination
                    :background="true"
                    :total="total"
                    :page-sizes="[5, 10, 15]"
                    layout="total, sizes, prev, pager, next, jumper"
                    v-model:page-size="pageSize"
                    v-model:current-page="pageNum"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"></el-pagination>
        </div>
    </div>

    <!-- 分配权限弹窗 -->
    <div>
        <el-dialog title="分配权限"
                   v-model="assignPermDialogVisible"
                   width="500px">

            <el-tree
                    style="max-width: 600px"
                    ref="permissionTree"
                    :data="data"
                    show-checkbox
                    node-key="id"
                    :default-expanded-keys="[2, 3]"
                    :default-checked-keys="permissionIds"
                    :props="defaultProps"></el-tree>
            <template #footer>
                <el-button @click="assignPermDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAssignPerm">保存</el-button>
            </template>
        </el-dialog>
    </div>

    <!-- 编辑角色弹窗 -->
    <div>
        <el-dialog title="编辑角色"
                   v-model="editDialogVisible"
                   width="450px">
            <el-form :model="editRoleForm"
                     ref="roleFormRef"
                     :rules="rules"
                     label-width="100px">
                <!-- id：禁用、只读 -->
                <el-form-item label="编号" prop="id">
                    <el-input v-model="editRoleForm.id" disabled></el-input>
                </el-form-item>
                <!-- 角色名称：可编辑 -->
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <!-- 角色编码：可编辑 -->
                <el-form-item label="角色编码" prop="roleCode">
                    <el-input v-model="editRoleForm.roleCode"></el-input>
                </el-form-item>
                <!-- 角色描述：可编辑 -->
                <el-form-item label="角色描述" prop="description">
                    <el-input v-model="editRoleForm.description" type="textarea"></el-input>
                </el-form-item>
                <!-- 创建时间：禁用、只读 -->
                <el-form-item label="创建时间" prop="createTime">
                    <el-input v-model="editRoleForm.createTime" disabled></el-input>
                </el-form-item>
<!--                &lt;!&ndash; 更新时间：禁用、只读，自动填充当前时间 &ndash;&gt;-->
<!--                <el-form-item label="更新时间" prop="updateTime">-->
<!--                    <el-input v-model="editRoleForm.updateTime" disabled></el-input>-->
<!--                </el-form-item>-->
            </el-form>
            <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleEditSubmit">提交</el-button>
            </template>
        </el-dialog>
    </div>
</div>

<script>

    const {createApp, ref, onMounted,nextTick,setCheckedKeys} = Vue;
    const {ElMessage,ElMessageBox} = ElementPlus;
    const app = createApp({
        setup() {
            // 表格数据（角色列表）
            const tableData = ref([]);
            // 分页参数
            const total = ref(0);
            const pageSize = ref(5);
            const pageNum = ref(1);
            // 分配权限弹窗显隐控制
            const assignPermDialogVisible = ref(false);

            // 分配权限弹窗默认勾选数据
            const  permissionIds= ref([]);
            //分配权限弹窗数据源
            const data= ref([])
            //弹窗引用
            const permissionTree=ref(null)
            // 树组件配置（标签、子节点字段映射）
            const defaultProps = {
                children: 'children',
                label: 'pname',
            }
            //选中的角色id
            const roleId=ref()

            //分配权限摁钮,获取分配权限弹窗数据
            const getPermissionData = (row) => {
                axios.get(`/permission/${row.id}`).then(resp => {
                    console.log("权限数据：", resp.data);
                    roleId.value=row.id;
                    //  先存储数据
                    data.value = resp.data.obj.allPermission;
                    permissionIds.value = resp.data.obj.permissionByRid;
                    //  显示弹窗（触发树组件渲染）
                    assignPermDialogVisible.value = true;
                    //  等待树组件渲染完成后，再设置勾选
                    nextTick(() => {
                            permissionTree.value.setCheckedKeys([], false);
                            permissionTree.value.setCheckedKeys(permissionIds.value, true);
                    });
                }).catch(error => {
                    ElMessage.error(error.response.data.msg);
                });
            }

            //编辑弹窗表单引用
            const roleFormRef = ref(null);
            //编辑角色弹窗显示控制
            const editDialogVisible=ref(false)
            // 编辑角色表单源数据
            const editRoleForm = ref({});
            // 编辑角色（空方法，保留结构）
            const handleEdit = (row) => {
                axios.get("/role/selectRole/"+row.id).then(resp=> {
                    if (resp.data.code === 200) {
                        editRoleForm.value = resp.data.obj;
                    }
                }).catch(error=>{
                    ElMessage.error(error.response.data.msg);
                })
                // 自动填充“更新时间”为当前日期（格式：YYYY-MM-DD）
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                editRoleForm.value.updateTime = `${year}-${month}-${day}`;
                editDialogVisible.value = true;
            };
            //提交编辑摁钮功能
            const handleEditSubmit = () => {
                roleFormRef.value.validate((valid) => {
                    if (valid) {
                        if (!roleFormRef.value.id) {
                            axios.post(`/role/updateRole`, editRoleForm.value).then(resp=>{
                                if (resp.data.code === 200) {
                                    ElMessage.success(resp.data.msg);
                                }
                                getRoles();
                                editDialogVisible.value = false;
                            })
                        }
                    }
                });
            }

            // 删除角色（空方法，保留结构）
            const handleDelete = (row) => {
                ElMessageBox.confirm('将永久删除该电影信息. 确定?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(() => {
                        axios.delete(`/role/deleteRole/${row.id}`).then(resp => {
                            if (resp.data.code === 200) {
                                ElMessage.success(resp.data.msg);
                                getRoles();
                            }
                        }).catch(error => {
                            ElMessage.error(error.response.data.msg);
                        })
                    })

            };


            // 保存权限分配（空方法，保留结构）
            const handleAssignPerm = () => {
                let pid1=permissionTree.value.getCheckedKeys();
                let pid2=permissionTree.value.getHalfCheckedKeys();
                let pid=pid1.concat(pid2);
                axios.post(`/permission/${roleId.value}`, pid).then(resp => {
                  if (resp.data.code === 200) {
                      ElMessage.success(resp.data.msg);
                      assignPermDialogVisible.value = false;
                  }
                }).catch(error => {
                    ElMessage.error(error.response.data.msg);
                    });
            };

            // 分页
            const handleSizeChange = (val) => {
                pageSize.value = val;
                getRoles();
            };
            const handlePageChange = (val) => {
                pageNum.value = val;
                getRoles();
            };

            //加载角色数据
            const getRoles = () => {
                axios.get(`/role/${pageNum.value}/${pageSize.value}`)
                    .then(resp=>{
                        tableData.value=resp.data.obj.data
                        total.value=resp.data.obj.total
                    })
                    .catch((error)=>{
                        ElMessage.error(error.response.data.msg)
                    })
            }

            // 表单验证规则
            const rules = ref({
                roleName: [
                    {required: true, message: '角色名称不能为空', trigger: 'blur'}
                ],
                roleCode: [
                    {required: true, message: '角色编码不能为空', trigger: 'blur'}
                ],
                description: [
                    {required: false, message: '角色描述可选', trigger: 'blur'}
                ]
            });

            onMounted(() => {
                getRoles();

            });

            return {
                data,
                tableData,
                total,
                pageSize,
                pageNum,
                assignPermDialogVisible,
                permissionIds,
                defaultProps,
                permissionTree,
                roleId,
                rules,
                roleFormRef,
                editRoleForm,
                editDialogVisible,
                handleEdit,
                handleDelete,
                getPermissionData,
                handleAssignPerm,
                handleSizeChange,
                handlePageChange,
                getRoles,
                handleEditSubmit,
            };
        }
    });
    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    });
    // 注册 Element Plus 图标
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }
    app.mount("#app");
</script>
</body>
</html>